package com.dbq.fast.util;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by yuanchen on 2018/4/13.
 */

public class FlashTimeHandler {
    private Timer timer;
    private IFlashTime listener;

    public void startTiming(int curPeriod, int timeCount){
        resetTimer();
        timer = new Timer();
        try {
            timer.schedule(new TimerTask() {
                AtomicInteger count = new AtomicInteger(timeCount);

                @Override
                public void run() {
                    if (count.get() < 0) {
                        if (listener != null) {
                            listener.timeOver(curPeriod);
                        }
                        resetTimer();
                        return;
                    }
                    listener.count(count.get());
                    count.decrementAndGet();
                }

            }, 0L, 1000L);
        }catch (Exception e){}
    }

    public void resetTimer() {
        if (timer != null) {
            synchronized (timer) {
                if (timer != null) {
                    timer.cancel();
                    timer.purge();
                    timer = null;
                }
            }
        }
    }

    public interface IFlashTime{
        void timeOver(int curPeriod);
        void count(int second);
    }

    public void setFlashTimeListener(IFlashTime listener){
        this.listener = listener;
    }

}
